<template>
  <el-drawer
    v-model="props.show_viewSetup"
    direction="rtl"
    size="70%"
    destroy-on-close
    @close="$emit('close_show_viewSetup')"
    :close-on-click-modal="false"
  >
    <template #title>
      <h4>视图配置</h4>
    </template>
    <template #default>
      <el-button @click="add_box = true" type="primary">新增</el-button>
      <el-table
        style="text-align: center; margin-top: 10px"
        :data="list"
        :max-height="max_height"
        border
        v-loading="loading"
      >
        <el-table-column
          label="序号"
          type="index"
          width="80px"
        ></el-table-column>
        <el-table-column label="名称" prop="name" sortable></el-table-column>
        <el-table-column label="类型" sortable prop="type">
          <template #default="scope: any">
            <div v-for="item in type_list" :key="item.id">
              <span v-if="item.id == scope.row.type">{{ item.name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope: any">
            <el-button @click="edit_list(scope)">编辑</el-button>
            <el-button @click="delete_list(scope)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="tr m_top10">
        <el-button type="primary" @click="$emit('close_show_viewSetup')"
          >确定</el-button
        >
      </div>
    </template>
  </el-drawer>
  <el-drawer
    v-model="add_box"
    direction="rtl"
    size="50%"
    destroy-on-close
    @close="resetForm(ruleViewSetupForm)"
    :close-on-click-modal="false"
  >
    <template #title>
      <h4 v-if="add_form_data.id == ''">新增视图</h4>
      <h4 v-else>编辑视图</h4>
    </template>
    <template #default>
      <el-form
        :model="add_form_data"
        ref="ruleViewSetupForm"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="视图类型">
          <el-select v-model="add_form_data.type">
            <el-option
              v-for="item in type_list"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="视图名称" prop="name">
          <el-input
            v-model="add_form_data.name"
            placeholder="请输入"
            show-word-limit
            maxlength="30"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="设备选择"
          v-if="add_form_data.type == 2"
          prop="deviceId"
        >
          <el-select v-model="add_form_data.deviceId" filterable>
            <el-option
              v-for="item in device_list"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="展示的元数据" prop="viewDetailIdList">
          <el-select
            v-model="add_form_data.viewDetailIdList"
            filterable
            multiple
            style="width: 100%"
            @change="get_viewDetailIdList()"
          >
            <div
              class="flex_js cp"
              style="padding: 0 10px 0 20px; height: 34px"
            >
              <el-checkbox
                v-model="all_select"
                class="m-l-20"
                :indeterminate="isIndeterminate"
                @change="select_all_view"
              >
                全选
              </el-checkbox>
            </div>
            <el-option
              v-for="item in view_list"
              :key="item.id"
              :value="item.id"
              :label="item.metadataNameShow"
            ></el-option>
          </el-select>
          <div
            class="metedata_box"
            v-if="add_form_data.viewDetailIdList.length"
          >
            <div>展示元数据配置</div>
            <el-table
              :data="add_form_data.viewDetailList"
              class="tc m_top10"
              max-height="600px"
              border
            >
              <el-table-column
                label="元数据名称"
                prop="metadataNameShow"
              ></el-table-column>
              <el-table-column label="编号" prop="code"></el-table-column>
              <el-table-column label="展示名称">
                <template #default="scope: any">
                  <el-input
                    v-model="scope.row.name"
                    placeholder="请输入"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column label="循环方式">
                <template #default="scope: any">
                  <el-select v-model="scope.row.loopCycle" placeholder="请输入">
                    <el-option
                      v-for="item in statisticsType_list"
                      :key="item.id"
                      :value="item.id"
                      :label="item.name"
                    ></el-option>
                    <el-option value="6" label="累加"></el-option>
                  </el-select>
                </template>
              </el-table-column>

              <el-table-column label="状态">
                <template #default="scope: any">
                  <el-select v-model="scope.row.isShow">
                    <el-option
                      :value="true"
                      :key="true"
                      label="展示"
                    ></el-option>
                    <el-option
                      :value="false"
                      :key="false"
                      label="隐藏"
                    ></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="判断方式" width="120px">
                <template #default="scope: any">
                  <el-select v-model="scope.row.judgmentType" clearable>
                    <el-option
                      v-for="item in judgment_type_list"
                      :key="item.id"
                      :value="item.id"
                      :label="item.name"
                    ></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="值">
                <template #default="scope: any">
                  <el-input
                    type="number"
                    :disabled="scope.row.judgmentType == ''"
                    v-model="scope.row.value"
                  ></el-input>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>

        <div v-if="add_form_data.type == 3 || add_form_data.type == 4">
          <el-form-item
            label="统计类型"
            v-if="add_form_data.type == 3 || add_form_data.type == 4"
          >
            <!-- 按时统计 只能求和 -->
            <el-select
              v-model="add_form_data.statisticsType"
              @change="change_statisticsType"
            >
              <el-option
                v-for="item in statisticsType_list"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="统计方式"
            v-if="add_form_data.type == 3 && add_form_data.statisticsType != 5"
          >
            <el-radio v-model="add_form_data.calculation" :label="1"
              >累计求和</el-radio
            >
            <el-radio v-model="add_form_data.calculation" :label="2"
              >累计平均</el-radio
            >
          </el-form-item>
          <el-form-item
            label="均值维度"
            v-if="add_form_data.type == 3 && add_form_data.calculation == 2"
          >
            <el-select v-model="add_form_data.avgType">
              <el-option
                :disabled="item.id < add_form_data.statisticsType"
                v-for="item in avgType_list"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="保留数据量"
            v-if="add_form_data.type == 3 && add_form_data.calculation == 1"
            prop="keepNumber"
          >
            <el-input
              v-model="add_form_data.keepNumber"
              type="number"
              placeholder="请输入(1~20)"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="日期类型"
            v-if="
              add_form_data.type == 3 &&
              [4, 5].includes(add_form_data.statisticsType) &&
              add_form_data.calculation == 1
            "
          >
            <el-select v-model="add_form_data.timeType">
              <el-option
                v-for="item in timeType_list"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            prop="values"
            :label="
              add_form_data.timeType == 2
                ? '固定星期'
                : add_form_data.timeType == 3
                ? '特定日期'
                : add_form_data.timeType
                ? '排除日期'
                : ''
            "
            v-if="
              [2, 3, 4].includes(add_form_data.timeType) &&
              [4, 5].includes(add_form_data.statisticsType) &&
              add_form_data.calculation == 1
            "
          >
            <el-select
              v-model="add_form_data.values[0]"
              v-if="add_form_data.timeType == 2"
            >
              <el-option
                v-for="item in week_list"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
            <el-date-picker
              v-else
              v-model="add_form_data.values"
              type="dates"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 100%"
              placeholder="请选择"
            />
          </el-form-item>
          <el-form-item
            label="指定时间"
            v-if="add_form_data.statisticsType == 5"
            prop="times"
          >
            <el-select
              v-model="add_form_data.times"
              multiple
              style="width: 100%"
            >
              <el-option
                v-for="item in time_list"
                :key="item"
                :value="item"
                :label="item"
              ></el-option>
            </el-select>
          </el-form-item>
        </div>
        <div class="m_top10 tr">
          <el-button @click="resetForm(ruleViewSetupForm)">取消</el-button>
          <el-button @click="submit(ruleViewSetupForm)" type="primary"
            >确定</el-button
          >
        </div>
      </el-form>
    </template>
  </el-drawer>
</template>

<script lang="ts" setup>
import { ref, onMounted, reactive, computed, nextTick, onUnmounted } from 'vue'
import { FormInstance, ElMessage, FormRules, ElMessageBox } from 'element-plus'
import axios from '@/service/HttpRequest'
import serviceApi from '@/service/api'
import EventBus from '@/utils/EventBus'
// type FormInstance = InstanceType<typeof ElForm>
const ruleViewSetupForm = ref<FormInstance>()
const rules = reactive<FormRules>({
  // 表单验证规则
  deviceId: [{ required: true, message: '请选择设备', trigger: 'change' }],
  name: [{ required: true, message: '请输入视图名称', trigger: 'blur' }],
  viewDetailIdList: [
    {
      required: true,
      type: 'array',
      message: '请选择元数据',
      trigger: 'change',
    },
  ],
  keepNumber: [
    { required: true, message: '请输入保留数据量', trigger: 'blur' },
  ],
  values: [
    { required: true, type: 'array', message: '请选择日期', trigger: 'change' },
  ],
  times: [
    { required: true, type: 'array', message: '请选择时间', trigger: 'change' },
  ],
})
const type_list = ref([
  { id: 1, name: '基础展示视图' },
  { id: 2, name: '设备展示视图' },
  { id: 3, name: '数据分析视图' },
  { id: 4, name: '统计列表视图' },
])
const statisticsType_list = ref([
  { id: 1, name: '按年' },
  { id: 2, name: '按月' },
  { id: 3, name: '按周' },
  { id: 4, name: '按日' },
  { id: 5, name: '按时' },
])
const change_statisticsType = (e) => {
  console.log(e)
  add_form_data.value.avgType = e
  add_form_data.value.values = []
  add_form_data.value.times = []
  e == 5
    ? ((add_form_data.value.avgType = 1), (add_form_data.value.calculation = 1))
    : ''
  add_form_data.value.viewDetailList.forEach((item) => {
    if (item.loopCycle == '') item.loopCycle = e
  })
}
const timeType_list = ref([
  { id: 1, name: '工作日' },
  { id: 2, name: '固定周几' },
  { id: 3, name: '特选日期' },
  { id: 4, name: '排除日期' },
  { id: 5, name: '每日' },
])
const avgType_list = ref([
  { id: 1, name: '按月平均' },
  { id: 2, name: '按周平均' },
  { id: 3, name: '按日平均' },
  { id: 4, name: '按时平均' },
])
const week_list = ref([
  { id: '1', name: '周一' },
  { id: '2', name: '周二' },
  { id: '3', name: '周三' },
  { id: '4', name: '周四' },
  { id: '5', name: '周五' },
  { id: '6', name: '周六' },
  { id: '7', name: '周日' },
])
const time_list = ref([]) // 按时 时间段列表
onMounted(() => {
  for (let i = 0; i <= 23; i++) {
    let item =
      (i < 10 ? '0' : '') +
      i +
      ':00' +
      '~' +
      (i + 1 < 10 ? '0' + (i + 1) : i + 1) +
      ':00'
    time_list.value.push(item)
  }
  console.log(time_list.value)
  EventBus.on('show_viewSetup', (e: any) => {
    projectId.value = e.projectId
    engineeringId.value = e.engineeringId
    get_list()
    get_device_list()
    get_engineeringMetadata_view_list()
  })
})
onUnmounted(() => {
  EventBus.off('show_viewSetup')
})
const all_select = computed(() => {
  return add_form_data.value.viewDetailIdList.length == view_list.value.length
})
const all_select_loading = ref(false)
const isIndeterminate = computed(() => {
  return (
    add_form_data.value.viewDetailIdList.length > 0 &&
    add_form_data.value.viewDetailIdList.length < view_list.value.length
  )
})
const select_all_view = () => {
  if (add_form_data.value.viewDetailList.length == view_list.value.length) {
    add_form_data.value.viewDetailList = []
    add_form_data.value.viewDetailIdList = []
  } else {
    all_select_loading.value = true
    let promise = new Promise((res, rej) => {
      view_list.value.forEach((item) => {
        if (!add_form_data.value.viewDetailIdList.includes(item.id)) {
          add_form_data.value.viewDetailIdList.push(item.id)
          let obj = {
            metadataNameShow: item.metadataNameShow,
            name: '',
            code: item.metadataCode,
            judgmentType: '',
            isShow: true,
            deviceMetadataId: item.id,
            metadataId: item.metadataId,
            sort: add_form_data.value.viewDetailList.length + 1,
            value: '',
            loopCycle: '',
          }
          add_form_data.value.viewDetailList.push(obj)
        }
      })
      res(1)
    })
    promise.then(() => {
      all_select_loading.value = false
    })
  }
}
const get_viewDetailIdList = () => {
  console.log(add_form_data.value.viewDetailIdList)
  add_form_data.value.viewDetailList.some((item, index) => {
    if (!add_form_data.value.viewDetailIdList.includes(item.deviceMetadataId)) {
      add_form_data.value.viewDetailList.splice(index, 1)
    }
  })
  let count = 0
  view_list.value.some((item) => {
    if (add_form_data.value.viewDetailIdList.includes(item.id)) {
      let flag = add_form_data.value.viewDetailList.some((item1) => {
        return item1.deviceMetadataId == item.id
      })
      if (!flag) {
        let obj = {
          metadataNameShow: item.metadataNameShow,
          name: '',
          code: item.metadataCode,
          judgmentType: '',
          isShow: true,
          deviceMetadataId: item.id,
          metadataId: item.metadataId,
          sort: add_form_data.value.viewDetailList.length + 1,
          value: '',
          loopCycle: '',
        }
        add_form_data.value.viewDetailList.push(obj)
        count += 1
      }
    }
    return count == add_form_data.value.viewDetailIdList.length
  })
}
const projectId = ref()
const engineeringId = ref()
const add_box = ref(false)
const loading = ref(false)
const list = ref()
const max_height = ref()
const props = defineProps({
  show_viewSetup: {
    type: Boolean,
  },
})
const add_form_data = ref({
  deviceId: '',
  type: 1,
  engineeringId: computed(() => {
    return engineeringId.value
  }),
  name: '',
  id: '',
  viewDetailIdList: [],
  viewDetailList: [],
  keepNumber: '', // 保留数据量
  statisticsType: 1, // 统计类型
  timeType: 1, // 时间类型
  values: [], // 特殊时间类型值
  calculation: 1, // 计算方式
  avgType: 1, // 均值维度
  times: [],
})
const judgment_type_list = ref([
  { id: 1, name: '等于' },
  { id: 2, name: '不等于' },
  { id: 3, name: '大于' },
  { id: 4, name: '大于等于' },
  { id: 5, name: '小于' },
  { id: 6, name: '小于等于' },
])
const delete_list = (e) => {
  ElMessageBox.confirm('确定删除该视图？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    closeOnClickModal: false,
    type: 'warning',
  })
    .then(() => {
      axios
        .request({
          url: serviceApi.szls_view_crud + '/' + e.row.id,
          method: 'delete',
        })
        .then(() => {
          ElMessage.success('操作成功！')
          setTimeout(() => {
            get_list()
          }, 1000)
        })
    })
    .catch(() => {})
}
const edit_list = (e) => {
  let list = []
  e.row.viewDetailList.forEach((item) => {
    list.push(item.deviceMetadataId)
    view_list.value.some((item1) => {
      if (item1.id == item.deviceMetadataId) {
        item.metadataNameShow = item1.metadataNameShow
        item.code = item1.metadataCode
      }
      return item1.id == item.deviceMetadataId
    })
  })
  console.log(e.row.viewDetailList)
  add_form_data.value = {
    deviceId: e.row.deviceId,
    type: e.row.type,
    name: e.row.name,
    id: e.row.id,
    engineeringId: engineeringId.value,
    viewDetailIdList: list,
    keepNumber: e.row.keepNumber ? e.row.keepNumber : '',
    statisticsType: e.row.statisticsType ? e.row.statisticsType : 1,
    timeType: e.row.timeType ? e.row.timeType : 1,
    values: e.row.viewTime?.valueList ? e.row.viewTime?.valueList : [],
    calculation: e.row.calculation ? e.row.calculation : 1,
    avgType: e.row.avgType
      ? e.row.avgType
      : e.row.statisticsType
      ? e.row.statisticsType
      : 1,
    times: e.row.viewTime?.timeList ? e.row.viewTime?.timeList : [],
    viewDetailList: e.row.viewDetailList,
  }
  add_box.value = true
}
const submit = async (formEl: FormInstance | undefined) => {
  await formEl.validate((valid) => {
    if (valid) {
      add_form_data.value.viewDetailList.forEach((item) => {
        item.name = item.name != '' ? item.name : item.metadataName
      })
      axios
        .request({
          url:
            add_form_data.value.id == ''
              ? serviceApi.szls_view_crud
              : serviceApi.szls_view_crud + '/' + add_form_data.value.id,
          method: add_form_data.value.id == '' ? 'post' : 'put',
          data: add_form_data.value,
        })
        .then((res) => {
          console.log(res)
          ElMessage.success('操作成功！')
          setTimeout(() => {
            add_box.value = false
            get_list()
            resetForm(formEl)
          }, 1000)
        })
    }
  })
}

const get_list = () => {
  loading.value = true
  axios
    .request({
      url: serviceApi.szls_view_list,
      method: 'post',
      data: { current: 1, pageSize: 100, engineeringId: engineeringId.value },
    })
    .then((res) => {
      list.value = res.data.content
      loading.value = false
    })
    .catch((err) => {
      ElMessage.error(err)
      loading.value = false
    })
}
nextTick(() => {
  max_height.value = window.innerHeight - 170
})
const resetForm = (formEl: FormInstance | undefined) => {
  console.log(123)
  if (!formEl) return
  formEl.resetFields()
  add_form_data.value = {
    deviceId: '',
    type: 1,
    engineeringId: engineeringId.value,
    name: '',
    id: '',
    viewDetailIdList: [],
    keepNumber: '',
    statisticsType: 1,
    timeType: 1,
    values: [],
    calculation: 1,
    avgType: 1,
    times: [],
    viewDetailList: [],
  }
  add_box.value = false
}
const device_list = ref()
const get_device_list = () => {
  axios
    .request({
      url: serviceApi.szls_device_view_list,
      method: 'post',
      data: {
        current: 1,
        pageSize: 1000,
        engineeringId: engineeringId.value,
      },
    })
    .then((res) => {
      console.log(res)
      device_list.value = res.data.content
    })
    .catch((err) => {
      ElMessage.error(err)
    })
}
const view_list = ref([])
const get_engineeringMetadata_view_list = () => {
  axios
    .request({
      url: serviceApi.szls_engineeringMetadata_view_list,
      method: 'post',
      data: {
        current: 1,
        pageSize: 1000,
        engineeringId: engineeringId.value,
        projectId: projectId.value,
        isCombination: true,
      },
    })
    .then((res) => {
      console.log(res)
      view_list.value = res.data === null ? [] : res.data
    })
}
</script>

<style lang="scss" scoped>
.metedata_box {
  border: 1px solid #dcdfe6;
  width: calc(100% - 20px);
  margin-top: 10px;
  padding: 0 10px 10px 10px;
  :deep(.el-input__inner) {
    padding-right: 11px;
  }
}
:deep(.el-tag) {
  line-height: 1.1;
}
</style>
